
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Sharepoint.ImportExport.Extractor;

namespace SharePoint.ImportExport.MigrationSuite
{
    public partial class ExportSettings : LayoutsPageBase
    {
        // add control fields to match controls tags on .aspx page
        protected Label lblStatus;
        protected Button btnExport;
        protected Button btnBack;
        protected TextBox txtListName;
        protected TextBox txtUncPath;
        protected TextBox txtSiteName;
        protected DropDownList drpDestinationDirectories;
        protected TextBox txtDirName;
        protected TextBox txtFolder;
        protected string returnValue;
        protected CheckBox chkIncludeSubsites;
        protected CheckBox chkIncludeUsers;
        protected CheckBox chkDateFilter;
        protected CheckBox chkDateFilter2;
        protected CheckBox chkUseTemplate;
        protected DateTimeControl dtcTime;
        protected DateTimeControl dtcTime2;
        protected CheckBox chkIncludeVersions;
        protected CheckBox chkIncludeDesignElements;

        protected Microsoft.SharePoint.WebControls.PeopleEditor userPicker;

        protected Microsoft.SharePoint.WebControls.TemplatePicker inputFormTemplatePickerControl;
        private bool loaded = false;
        private string exportSiteURL = String.Empty;


        void btnExport_Click(object sender, EventArgs e)
        {
            string exportDirectory = this.txtUncPath.Text;
            if (exportDirectory.Length == 0)
            {
                exportDirectory = this.drpDestinationDirectories.Text + "\\" + txtDirName.Text;
            }

            if (exportDirectory.Length == 0)
            {
                this.lblStatus.Text = "You need to specify the export directory";
                return;
            }

            if (this.userPicker.Entities.Count < 1)
            {
                this.lblStatus.Text = "You need to choose a site owner";
                return;
            }

            if (this.txtSiteName.Text.StartsWith("http"))
            {
                this.lblStatus.Text = "The site name field should not contain an URL";
                return;
            }

            Uri uri = new Uri(this.Web.Url);
            string managedpath = this.Web.Url;
            int pos=managedpath.IndexOf(uri.Host);
            if(pos>0)
            {
                managedpath=managedpath.Substring(pos+uri.Host.Length);
            }

            if (managedpath.StartsWith("/"))
            {
                managedpath = managedpath.Substring(1);
                managedpath = managedpath.Substring(0, managedpath.IndexOf("/"));
            }
            else
            {
                managedpath = String.Empty;
            }

            string newPage = this.Web.Url + "/_layouts/settings.aspx";
            Exporter extractor = new Exporter();
            string logFileName=exportDirectory+ "\\export - " + DateTime.Now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture) + ".log";
            if (extractor.Init(false, logFileName))
            {
                using (SPLongOperation op = new SPLongOperation(this))
                {
                    op.LeadingHTML = "Exporting Site " + this.Web.Title + " to folder " + exportDirectory;
                    op.Begin();

                    SPUtility.ValidateFormDigest();
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                     {
                         DataSet ds = new DataSet("Export Parameters");
                         DataTable dt = ds.Tables.Add("Parameters");
                         dt.Columns.Add("SiteURL", typeof(System.String));
                         dt.Columns.Add("OutputDirectory", typeof(System.String));
                         dt.Columns.Add("SiteName", typeof(System.String));
                         dt.Columns.Add("List", typeof(System.String));
                         dt.Columns.Add("Owner", typeof(System.String));
                         dt.Columns.Add("Contact", typeof(System.String));
                         dt.Columns.Add("IncludeSubWebs", typeof(System.Boolean));
                         dt.Columns.Add("ManagedPath", typeof(System.String));
                         dt.Columns.Add("SiteDef", typeof(System.String));
                         dt.Columns.Add("Folder", typeof(System.String));
                         dt.Columns.Add("ExportDesign", typeof(System.Boolean));
                         dt.Columns.Add("ExportUsers", typeof(System.Boolean));
                         dt.Columns.Add("ExportItemsNewerThan", typeof(System.DateTime));
                         dt.Columns.Add("ExportItemsOlderThan", typeof(System.DateTime));
                         dt.Columns.Add("ExportVersions", typeof(System.Boolean));
                         dt.Columns.Add("ExportDoclibsOnly", typeof(System.Boolean));
                         dt.Columns.Add("ProcessGalleries", typeof(System.Boolean));
                         dt.Columns.Add("ExportViews", typeof(System.Boolean));

                         DataRow newRow = dt.NewRow();

                         PickerEntity pickEn = (PickerEntity)this.userPicker.Entities[0];
                         Hashtable hstEntityData = pickEn.EntityData;

                         // Set values in the columns:
                         newRow["SiteURL"] = this.Web.Url;
                         newRow["OutputDirectory"] = exportDirectory;

                         newRow["SiteName"] = this.txtSiteName.Text;
                         newRow["List"] = this.txtListName.Text.Trim();
                         newRow["Owner"] = pickEn.Key;
                         newRow["Contact"] = Convert.ToString(hstEntityData["Email"]);
                         newRow["IncludeSubWebs"] = this.chkIncludeSubsites.Checked;
                         newRow["ManagedPath"] = managedpath;

                         if (this.txtFolder.Text.Length > 0 && this.txtListName.Text.Length == 0)
                         {
                             this.lblStatus.Text = "You cannot export a subfolder without specifying the list/library name";
                             return;
                         }

                         if (this.chkUseTemplate.Checked)
                         {
                             newRow["SiteDef"] = this.inputFormTemplatePickerControl.SelectedWebTemplate;
                         }

                         newRow["Folder"] = this.txtFolder.Text.Trim();
                         newRow["ExportDesign"] = this.chkIncludeDesignElements.Checked;
                         newRow["ExportUsers"] = this.chkIncludeUsers.Checked;
                         if (this.chkDateFilter.Checked)
                         {
                             newRow["ExportItemsNewerThan"] = this.dtcTime.SelectedDate;
                         }
                         else
                         {
                             newRow["ExportItemsNewerThan"] = DateTime.MinValue;
                         }

                         if (chkDateFilter2.Checked)
                         {
                             newRow["ExportItemsOlderThan"] = this.dtcTime2.SelectedDate;
                         }
                         else
                         {
                             newRow["ExportItemsOlderThan"] = DateTime.MinValue;
                         }

                         newRow["ExportVersions"] = this.chkIncludeVersions.Checked;
                         newRow["ExportDoclibsOnly"] = false;
                         newRow["ProcessGalleries"] = false;
                         newRow["ExportViews"] = false;

                         // Add the row to the rows collection.
                         dt.Rows.Add(newRow);

                         try
                         {
                             string resultData = extractor.Process(ds);
                             extractor.Close();
                             lblStatus.Text = resultData + "|" + this.exportSiteURL;
                             if (resultData.StartsWith("Exported"))
                             {
                                 bool listExists = false;
                                 Guid listID = Guid.Empty;
                                 try
                                 {
                                     using (Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite(this.exportSiteURL))
                                     {
                                         using (Microsoft.SharePoint.SPWeb web = site.RootWeb)
                                         {
                                             foreach (Microsoft.SharePoint.SPList list in web.Lists)
                                             {
                                                 if (list.Title == "ExportedData")
                                                 {
                                                     listExists = true;
                                                     listID = list.ID;

                                                     newPage = list.DefaultViewUrl;
                                                     break;
                                                 }

                                             }
                                             if (!listExists)
                                             {
                                                 listID = web.Lists.Add("ExportedData", "This contains the export info for the list", SPListTemplateType.GenericList);

                                             }
                                             if (listID != Guid.Empty)
                                             {
                                                 Microsoft.SharePoint.SPList list = web.Lists[listID];
                                                 newPage = list.DefaultViewUrl;

                                                 if (!list.Fields.ContainsField("ExportDirectory"))
                                                 {
                                                     list.Fields.Add("ExportDirectory", SPFieldType.Text, true);
                                                     list.Fields.Add("SiteInclusionPath", SPFieldType.Text, true);
                                                     list.Fields.Add("SiteDefinitionName", SPFieldType.Text, true);
                                                     list.Fields.Add("SiteOwner", SPFieldType.Text, false);
                                                     list.Fields.Add("SiteURL", SPFieldType.URL, false);
                                                     list.Fields.Add("Contact", SPFieldType.Text, false);
                                                     list.Fields.Add("IncludeSubSites", SPFieldType.Boolean, true);
                                                     list.Fields.Add("IncludeUserInfo", SPFieldType.Boolean, true);

                                                     list.Fields.Add("ListName", SPFieldType.Text, false);
                                                     list.Fields.Add("FolderName", SPFieldType.Text, false);
                                                     list.Fields.Add("ExportItemsNewerThan", SPFieldType.DateTime, false);
                                                     list.Fields.Add("ExportItemsOlderThan", SPFieldType.DateTime, false);
                                                     list.Fields.Add("IncludeVersions", SPFieldType.Boolean, false);
                                                     list.Fields.Add("Result", SPFieldType.Text, false);
                                                 }

                                                 Microsoft.SharePoint.SPListItem item = list.Items.Add();

                                                 item["Title"] = this.txtSiteName.Text;
                                                 item.Update();
                                                 item["ExportDirectory"] = drpDestinationDirectories.Text + "\\" + txtDirName.Text;
                                                 if (this.txtListName.Text.Length > 1)
                                                 {
                                                     item["ListName"] = this.txtListName.Text;
                                                 }
                                                 else
                                                 {
                                                     item["ListName"] = " ";
                                                 }
                                                 if (this.txtFolder.Text.Length > 1)
                                                     item["FolderName"] = this.txtFolder.Text;
                                                 else
                                                     item["FolderName"] = " ";
                                                 item["SiteOwner"] = pickEn.Key;
                                                 item["Contact"] = Convert.ToString(hstEntityData["Email"]);

                                                 item["IncludeSubSites"] = this.chkIncludeSubsites.Checked;
                                                 item["IncludeUserInfo"] = this.chkIncludeUsers.Checked;

                                                 item["SiteInclusionPath"] = managedpath;
                                                 if (managedpath.Length > 0)
                                                 {
                                                     item["SiteURL"] = "http://" + uri.Host + ":" + uri.Port.ToString() + "/" + managedpath + "/" + this.txtSiteName.Text;
                                                 }
                                                 else
                                                 {
                                                     item["SiteURL"] = "http://" + uri.Host + ":" + uri.Port.ToString() + "/" + this.txtSiteName.Text;
                                                 }

                                                 if (this.chkUseTemplate.Checked)
                                                 {
                                                     item["SiteDefinitionName"] = this.inputFormTemplatePickerControl.SelectedWebTemplate;
                                                 }
                                                 if (this.chkDateFilter.Checked)
                                                 {
                                                     if (this.dtcTime.SelectedDate != DateTime.MinValue)
                                                     {
                                                         item["ExportItemsNewerThan"] = this.dtcTime.SelectedDate;
                                                     }
                                                 }

                                                 if (this.chkDateFilter2.Checked)
                                                 {
                                                     if (this.dtcTime2.SelectedDate != DateTime.MinValue)
                                                     {
                                                         item["ExportItemsOlderThan"] = this.dtcTime2.SelectedDate;
                                                     }
                                                 }

                                                 item["IncludeVersions"] = this.chkIncludeVersions.Checked;
                                                 item["Result"] = resultData;

                                                 item.Update();

                                                 try
                                                 {
                                                     using (FileStream attachmentStream = new FileStream(logFileName, FileMode.Open, FileAccess.Read))
                                                     {
                                                         if (attachmentStream.Length > 0)
                                                         {
                                                             BinaryReader binaryAttachmentReader = new BinaryReader(attachmentStream);
                                                             byte[] attachmentFileBytes = binaryAttachmentReader.ReadBytes((int)attachmentStream.Length);
                                                             item.Attachments.Add("Results.log", attachmentFileBytes);
                                                         }
                                                     }
                                                     //File.Delete(logFileName);
                                                 }
                                                 catch (Exception Ex)
                                                 {
                                                 }
                                                 
                                                 item.BreakRoleInheritance(false);
                                                 SPRoleAssignment roleAssignement = new SPRoleAssignment(web.CurrentUser.LoginName, web.CurrentUser.Email, web.CurrentUser.Name, "");
                                                 SPRoleDefinition roleDefinition = web.RoleDefinitions["Full Control"];
                                                 roleAssignement.RoleDefinitionBindings.Add(roleDefinition);
                                                 item.RoleAssignments.Add(roleAssignement);

                                                 roleAssignement = new SPRoleAssignment(web.SiteAdministrators[0].LoginName, web.SiteAdministrators[0].Email, web.SiteAdministrators[0].Name, "");
                                                 roleAssignement.RoleDefinitionBindings.Add(roleDefinition);
                                                 item.RoleAssignments.Add(roleAssignement);
                                                 item.Update();

                                                 newPage = this.exportSiteURL + "/Lists/ExportedData/DispForm.aspx?ID=" + item.ID.ToString();
                                                 lblStatus.Text = newPage;
                                             }
                                         }
                                     }
                                 }
                                 catch (SPException spEx)
                                 {
                                     this.lblStatus.Text = "Error occurred when saving item: " + this.txtSiteName.Text + ". Error: " + spEx.Message;
                                 }
                             }

                         }
                         catch (Exception Ex)
                         {
                             this.lblStatus.Text = "Exception occurred :" + Ex.Message;

                         }
                     });
                    op.End(newPage,SPRedirectFlags.Trusted,this.Context,"");
                }
            }
        }

        protected override void OnInitComplete(EventArgs e)
        {
            if (this.loaded)
            {
                return;
            }
            this.loaded = true;

            try
            {
                this.btnExport.Click += new EventHandler(this.btnExport_Click);
                Microsoft.SharePoint.SPWeb site = this.Web;
                this.btnBack.PostBackUrl = site.Url;
                if (this.drpDestinationDirectories.Items.Count == 0)
                {
                    ExportLocationService service = ExportLocationService.Local;
                    if (service != null)
                    {
                        foreach (ContentLocation loc in service.Locations)
                        {
                            if (loc.DisplayName == "MigrationSuite.Site")
                            {
                                this.exportSiteURL = loc.Url;
                            }

                            if (loc.DisplayName == "MigrationSuite.Directories")
                            {
                                string data = loc.Url;
                                foreach (string s in data.Split(';'))
                                {
                                    this.drpDestinationDirectories.Items.Add(s);
                                }
                            }
                        }
                    }

                }

                try
                {
                    Microsoft.SharePoint.SPList list = Web.Lists["ExportedData"];
                    if (list.ItemCount > 1)
                    {
                        Microsoft.SharePoint.SPListItem item = list.Items[list.ItemCount - 1];
                        this.txtSiteName.Text = item["Title"].ToString();
                        foreach (Microsoft.SharePoint.SPField f in item.Fields)
                        {
                            string s = f.InternalName;
                        }

                        PickerEntity pickEn = new PickerEntity();
                        pickEn.Key = item["SiteOwner"].ToString();
                        this.userPicker.Entities.Add(this.userPicker.ValidateEntity(pickEn));

                        this.chkIncludeSubsites.Checked = Convert.ToBoolean(item["IncludeSubSites"]);
                        this.chkIncludeUsers.Checked = Convert.ToBoolean(item["IncludeUserInfo"]);

                        this.chkIncludeVersions.Checked = Convert.ToBoolean(item["IncludeVersions"]);
                        this.txtListName.Text = item["ListName"].ToString();
                        this.txtFolder.Text = item["FolderName"].ToString();
                        string sdir = item["ExportDirectory"].ToString();
                        foreach (ListItem li in this.drpDestinationDirectories.Items)
                        {
                            if (sdir.StartsWith(li.Text))
                            {
                                ////Choose the longest match
                                if (li.Text.Length > this.drpDestinationDirectories.Text.Length) 
                                {
                                    this.drpDestinationDirectories.Text = li.Text;
                                    this.txtDirName.Text = sdir.Substring(sdir.IndexOf(li.Text) + 1 + li.Text.Length);
                                }
                            }

                        }
                    }
                }
                catch (Exception Ex)
                {
                }

            }
            catch (Exception Ex)
            {

            }

        }

    }
}
